package com.chc.web.menu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chc.utils.Msg;
import com.chc.web.menu.entity.Menu;
import com.chc.web.menu.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/api/menu")
@RestController
public class MenuController {
    @Autowired
    MenuService menuService;


    //树数据列表
    @GetMapping("/list")
    public Msg list(){
        List<Menu> list = menuService.getList();
        return Msg.success("查询成功",list);
    }

    //新增菜单
    @PostMapping
    public Msg addMenu(@RequestBody Menu menu){
        boolean save = menuService.save(menu);
        if (save){
            return Msg.success("新增菜单成功!");
        }else {
            return Msg.error("新增菜单失败!");
        }
    }

    //新增菜单
    @PutMapping
    public Msg editMenu(@RequestBody Menu menu){
        boolean save = menuService.updateById(menu);
        if (save){
            return Msg.success("编辑菜单成功!");
        }else {
            return Msg.error("编辑菜单失败!");
        }
    }

    //删除菜单
    @DeleteMapping("/{menuId}")
    public Msg editMenu(@PathVariable("menuId") Long menuId){
        QueryWrapper<Menu> query = new QueryWrapper<>();
        query.lambda().eq(Menu::getParentId,menuId);
        List<Menu> list = menuService.list(query);
        if (list.size() > 0){
            return Msg.error("该菜单存在下级，不能删除!");
        }
        boolean b = menuService.removeById(menuId);
        if (b){
            return Msg.success("删除菜单成功!");
        }else {
            return Msg.error("删除菜单失败!");
        }
    }

    //获取上级菜单
    @GetMapping("/parent")
    public Msg getParent(){
        List<Menu> parentList = menuService.getParentList();
        return Msg.success("查询成功",parentList);
    }

}
